package com.mxx.exceltoentity.print;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.mxx.exceltoentity.trans.BaiduDomain;
import com.mxx.exceltoentity.trans.BaiduResult;
import com.mxx.exceltoentity.trans.TransApi;
import com.mxx.exceltoentity.ui.TuantDialog;
import com.mxx.exceltoentity.util.SimpleConfigUtil;
import it.unimi.dsi.fastutil.Pair;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.io.UnsupportedEncodingException;
import java.util.*;

public class CalculationPrint {
    public static Log log = LogFactory.getLog(CalculationPrint.class);
    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer

    private static String translate(String query) throws UnsupportedEncodingException {
        return TransApi.getTransResult(query, "auto", "en");
    }

    public static String printSql(String txt, JLabel label) throws Exception {
        txt = checktxt(txt);
        if (StringUtils.isBlank(txt)) {
            return txt;
        }
        String[] txtArr = txt.split("：");
        String tableName = txtArr[0];
        String fieldStr = txtArr[1];
        StringBuilder sqlAppend = new StringBuilder();
        StringBuilder beanAppend = new StringBuilder();
        Map<String, String> filedMap = new LinkedHashMap<>();
        Pair<String, String> namePair = null;
        String[] fieldArr = fieldStr.split("\\s+");
        ArrayList<String> str = new ArrayList<>();
        str.add(tableName);
        str.addAll(Arrays.asList(fieldArr));
        int length = fieldArr.length;
        for (int i = 0; i < str.size(); i++) {
            String fieldCh = str.get(i);
            String translateText = CalculationPrint.translate(fieldCh);
            log.warn(translateText);
            label.setText("倒计时：" + length);
            length--;
            label.repaint();
            Thread.sleep(1000);
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(translateText, Map.class);
            if ("58000".equals(map.get("error_code"))) {
                EventQueue.invokeLater(() -> {
                    Map data = (Map) map.get("data");
                    new TuantDialog("请将IP：" + data.get("client_ip") + " 添加到百度翻译平台：http://api.fanyi.baidu.com/manage/developer").show();
                });
                break;
            }
            if (Objects.nonNull(map.get("error_code"))) {
                EventQueue.invokeLater(() -> {
                    new TuantDialog("百度翻译接口出错：返回信息：" + translateText).show();
                });
                break;
            }
            BaiduDomain baiduDomain = mapper.readValue(translateText, BaiduDomain.class);
            BaiduResult baiduResult = baiduDomain.getTrans_result().get(0);
            String dst = baiduResult.getDst();
            if (i == 0) {
                namePair = Pair.of(dst.toLowerCase().replaceAll("\\s+", "_"), fieldCh);
            } else {
                filedMap.put(fieldCh, dst.toLowerCase().replaceAll("\\s+", "_").replaceAll("[^a-zA-Z0-9]", "_"));
            }
        }
        sqlAppend.append("\n/**\n");
        sqlAppend.append("drop table if exists ").append(namePair.key()).append(";\n");
        sqlAppend.append("CREATE TABLE ").append("`").append(namePair.key()).append("`").append(" ( \n");
        sqlAppend.append("`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',\n" +
                "`creator` varchar NOT NULL DEFAULT '' COMMENT '创建人',\n" +
                "`last_updater` varchar NOT NULL DEFAULT '' COMMENT '更新人',\n" +
                "`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建日期',\n" +
                "`last_updated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新日期',\n");
        beanAppend.append("import lombok.AllArgsConstructor;\n");
        beanAppend.append("import lombok.Data;\n");
        beanAppend.append("import lombok.NoArgsConstructor;\n");
        beanAppend.append("import java.util.Date;\n");
        beanAppend.append("\n");
        beanAppend.append("@Data\n");
        beanAppend.append("@NoArgsConstructor\n");
        beanAppend.append("@AllArgsConstructor\n");
        beanAppend.append("public class ").append(underlineToHump(namePair.key(), true)).append(" {\n");
        beanAppend.append("    \n");
        beanAppend.append("    /**\n");
        beanAppend.append("     * 主键\n");
        beanAppend.append("    */\n");
        beanAppend.append("    private Long id;\n");
        beanAppend.append("    \n");
        beanAppend.append("    /**\n");
        beanAppend.append("     * 创建人\n");
        beanAppend.append("     */\n");
        beanAppend.append("    private String creator;\n");
        beanAppend.append("    \n");
        beanAppend.append("    /**\n");
        beanAppend.append("     * 更新人\n");
        beanAppend.append("     */\n");
        beanAppend.append("    private String lastUpdater;\n");
        beanAppend.append("    \n");
        beanAppend.append("    /**\n");
        beanAppend.append("     * 创建日期\n");
        beanAppend.append("     */\n");
        beanAppend.append("    private Date dateCreated;\n");
        beanAppend.append("    \n");
        beanAppend.append("    /**\n");
        beanAppend.append("     * 更新日期\n");
        beanAppend.append("    \n");
        beanAppend.append("     */\n");
        beanAppend.append("    private Date lastUpdated;\n");

        for (Map.Entry<String, String> stringStringEntry : filedMap.entrySet()) {
            String chinese = stringStringEntry.getKey();
            String eng = stringStringEntry.getValue();
            beanAppend.append("    \n");
            beanAppend.append("    /**\n");
            beanAppend.append("     * ").append(chinese).append("\n");
            beanAppend.append("     */\n");
            if (chinese.contains("数量") || chinese.contains("个数")) {
                sqlAppend.append("`").append(eng).append("`").append(" ");
                sqlAppend.append("int(10) unsigned NOT NULL DEFAULT 0 comment '").append(chinese).append("'");
                sqlAppend.append(",\n");
                beanAppend.append("    private Integer ").append(underlineToHump(eng)).append(";\n");
            } else if (chinese.endsWith("金") || chinese.endsWith("率") || chinese.endsWith("比例") || chinese.contains("税") || chinese.endsWith("费用")) {
                sqlAppend.append("`").append(eng).append("`").append(" ");
                sqlAppend.append(" decimal(16,2) NOT NULL DEFAULT '0.00' comment '").append(chinese).append("'");
                sqlAppend.append(",\n");
                beanAppend.insert(0, "import java.math.BigDecimal;\n");
                beanAppend.append("    private BigDecimal ").append(underlineToHump(eng)).append(";\n");
            } else if (chinese.contains("时间") || chinese.contains("日期")) {
                sqlAppend.append("`").append(eng).append("`").append(" ");
                sqlAppend.append(" datetime NOT NULL DEFAULT '1970-01-01 00:00:00' comment '").append(chinese).append("'");
                sqlAppend.append(",\n");
                beanAppend.append("    private Date ").append(underlineToHump(eng)).append(";\n");
            } else {
                sqlAppend.append("`").append(eng).append("`").append(" ");
                sqlAppend.append("varchar NOT NULL DEFAULT '' comment '").append(chinese).append("'");
                sqlAppend.append(",\n");
                beanAppend.append("    private String ").append(underlineToHump(eng)).append(";\n");
            }
        }
        sqlAppend.append("PRIMARY KEY (`id`)\n");
        sqlAppend.append(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='").append(namePair.value()).append("';\n");

        sqlAppend.append("     */\n");
        beanAppend.append("}\n");
        sqlAppend.append(beanAppend);
        return sqlAppend.toString();
    }

    @Nullable
    private static String checktxt(String txt) {
        if (StringUtils.isBlank(txt) || !txt.contains("：") || txt.split("：").length != 2) {
            EventQueue.invokeLater(() -> {
                new TuantDialog("输入文本格式不正确。例：人员：姓名 年龄 地址").show();
            });
            return "";
        }
        String appid = SimpleConfigUtil.getString("key");
        String securityKey = SimpleConfigUtil.getString("value");
        if (StringUtils.isBlank(appid) || StringUtils.isBlank(securityKey)) {
            EventQueue.invokeLater(() -> {
                new TuantDialog("请先在Settings->Tools->Excel to entity进行配置").show();
            });
            return "";
        }
        return txt;
    }

    /**
     * 下划线转换为驼峰
     *
     * @param line             下划线字符串
     * @param firstIsUpperCase 首字母是否转换为大写
     * @return
     */
    private static String underlineToHump(String line, boolean... firstIsUpperCase) {
        String str = "";

        if (StringUtils.isBlank(line)) {
            return str;
        } else {
            StringBuilder sb = new StringBuilder();
            String[] strArr;
            // 不包含下划线，且第二个参数是空的
            if (!line.contains("_") && firstIsUpperCase.length == 0) {
                sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1));
                str = sb.toString();
            } else if (!line.contains("_") && firstIsUpperCase.length != 0) {
                if (!firstIsUpperCase[0]) {
                    sb.append(line.substring(0, 1).toLowerCase()).append(line.substring(1));
                    str = sb.toString();
                } else {
                    sb.append(line.substring(0, 1).toUpperCase()).append(line.substring(1));
                    str = sb.toString();
                }
            } else if (line.contains("_") && firstIsUpperCase.length == 0) {
                strArr = line.split("_");
                for (String s : strArr) {
                    sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
                }
                str = sb.toString();
                str = str.substring(0, 1).toLowerCase() + str.substring(1);
            } else if (line.contains("_") && firstIsUpperCase.length != 0) {
                strArr = line.split("_");
                for (String s : strArr) {
                    sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
                }
                if (!firstIsUpperCase[0]) {
                    str = sb.toString();
                    str = str.substring(0, 1).toLowerCase() + str.substring(1);
                } else {
                    str = sb.toString();
                }
            }
        }
        str = str.replace("0", "Zero");
        str = str.replace("1", "One");
        str = str.replace("2", "Two");
        str = str.replace("3", "Three");
        str = str.replace("4", "Four");
        str = str.replace("5", "Five");
        str = str.replace("6", "Six");
        str = str.replace("7", "Seven");
        str = str.replace("8", "Eight");
        str = str.replace("9", "Nine");

        return str;
    }

}
